package gupao.concurrency.demo.risk.model;


import java.util.*;

public class NodeTree {
    private Map<Integer, List<Node>> levelMap = new HashMap<>();
    private int maxLevel;
    private int minLevel = 0;

    public List<Node> getChildren(Node parent){
        if(parent.getLevel() == minLevel){
            return Collections.emptyList();
        }
        List<Node> nextLevel = levelMap.get(parent.getLevel() - 1);
        List<Node> children = new ArrayList<>();
        nextLevel.forEach(c -> {
            if(parent.getNodeId().equals(c.getParentId())){
                children.add(c);
            }
        });
        return children;
    }

    public static NodeTree buildTree(List<Node> nodeList){
        NodeTree tree = new NodeTree();
        Map<Integer, List<Node>> map = tree.getLevelMap();
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for (Node node : nodeList) {
            List<Node> levelList = map.computeIfAbsent(node.getLevel(), l -> new ArrayList<>());
            levelList.add(node);
            min = Math.min(min, node.getLevel());
            max = Math.max(max, node.getLevel());
        }
        tree.setMaxLevel(max);
        tree.setMinLevel(min);
        return tree;
    }

    public Map<Integer, List<Node>> getLevelMap() {
        return levelMap;
    }

    public void setLevelMap(Map<Integer, List<Node>> levelMap) {
        this.levelMap = levelMap;
    }

    public int getMaxLevel() {
        return maxLevel;
    }

    public void setMaxLevel(int maxLevel) {
        this.maxLevel = maxLevel;
    }

    public int getMinLevel() {
        return minLevel;
    }

    public void setMinLevel(int minLevel) {
        this.minLevel = minLevel;
    }
}
